package com.itheima.service.impl;

import cn.hutool.core.util.IdUtil;
import com.itheima.common.Com.ShoppingCart;
import com.itheima.common.vo.ShoppingCartDto;
import com.itheima.common.vo.ShoppingCartVo;
import com.itheima.mapper.ShoppingCartMapper;
import com.itheima.service.ShoppingCartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class ShoppingCartServiceImpl implements ShoppingCartService {
    @Autowired
    private ShoppingCartMapper shoppingCartMapper;
    @Override
    public List<ShoppingCart> getAll() {

        List<ShoppingCart> all = shoppingCartMapper.getAll();
        return all;
    }

    @Override
    public ShoppingCartVo save(ShoppingCart shoppingCart) {

        String name = shoppingCart.getName();
        ShoppingCart shoppingCartVo = shoppingCartMapper.selectOne(name);
        if (shoppingCartVo!=null){
           shoppingCartVo.setNumber(shoppingCartVo.getNumber()+1);
            boolean update = shoppingCartMapper.update(shoppingCartVo);
            return shoppingCartMapper.findById(shoppingCartVo.getId());

        }

        shoppingCart.setId(IdUtil.getSnowflakeNextIdStr());
        shoppingCart.setNumber(1);


        shoppingCartMapper.save(shoppingCart);

        return shoppingCartMapper.findById(shoppingCart.getId());
    }

    @Override
    public boolean delete() {

        shoppingCartMapper.delete();
        return true;
    }

    @Override
    public boolean deleteId(ShoppingCartDto shoppingCartDto) {

        ShoppingCart select = shoppingCartMapper.select(shoppingCartDto);
        if (select.getNumber()>1){
            select.setNumber(select.getNumber()-1);
           return shoppingCartMapper.update(select);
        }

        boolean b = shoppingCartMapper.deleteId(shoppingCartDto);
        return b;
    }
}
